package com.xmgps.speech.service;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Author: Wang Shao Kui
 * Create date: 2021/7/8 - 11:50
 * Description:
 */
@Component
public class XunFeiSpeechUtil {

    @Value("${speech.save.url}")
    private String saveFileUrl;
    @Value("${speech.work.url}")
    private String workFileUrl;
    @Value("${speech.dll.url}")
    private String ddlFileUrl;
    @Value("${speech.userRes.url}")
    private String userResFileUrl;
    @Value("${speech.commonRes.url}")
    private String commonResFileUrl;
    @Value("${speech.engineType}")
    private String engineType;

    Logger logger = LoggerFactory.getLogger(XunFeiSpeechUtil.class);

    public void createFile(String name) {
        MscLibrary INSTANCE = Native.load(ddlFileUrl, MscLibrary.class);

        //登录参数,appid与msc库绑定,请勿随意改动
        String login_params = "appid = 81857cc8, work_dir = " + workFileUrl;
        //合成参数：tts_res_path我这里用了绝对路径
        String session_begin_params = "engine_type = %s,voice_name=xiaoyan,  voice_name = xiaoyan, text_encoding = UTF-8, " +
                "tts_res_path = fo|%s;fo|%s, " +
                "sample_rate = 16000, speed = 50, volume = 50, pitch = 50, rdn = 2";
        session_begin_params = String.format(session_begin_params,engineType, userResFileUrl, commonResFileUrl);
        //合成的语音文件名称
        String filename = saveFileUrl + File.separator + "tts_sample.wav";
        //合成文本
        logger.info("fileName: {}", filename);
        String sessionId = null;
        RandomAccessFile raf = null;
        try {
            logger.info("开始登录");
            //登录
            int loginCode = INSTANCE.MSPLogin(null, null, login_params);

            if (loginCode != 0) {
                logger.error("登录失败");
                //登录失败
                return;
            }

            //初始session
            IntByReference errCode = new IntByReference();
            sessionId = INSTANCE.QTTSSessionBegin(session_begin_params, errCode);

            if (errCode.getValue() != 0) {
                logger.error("会话失败");
                //会话失败
                return;
            }

            //放入文本
            int textPutCode = INSTANCE.QTTSTextPut(sessionId, name, name.getBytes().length, null);

            if (textPutCode != 0) {
                logger.error("放入文本失败:{}", textPutCode);
                //放入文本失败
                return;
            }

            //写入空的头格式
            raf = new RandomAccessFile(filename, "rw");
            raf.write(new byte[44]);
            int dataSize = 0;
            IntByReference audioLen = new IntByReference();
            IntByReference synthStatus = new IntByReference();
            while (true) {
                Pointer pointer = INSTANCE.QTTSAudioGet(sessionId, audioLen, synthStatus, errCode);
                if (pointer != null && audioLen.getValue() > 0) {
                    //写入合成内容
                    raf.write(pointer.getByteArray(0, audioLen.getValue()));
                    //记录数据长度
                    dataSize += audioLen.getValue();
                }
                //转换异常或转换结束跳出循环
                if (errCode.getValue() != 0 || synthStatus.getValue() == 2) {
                    break;
                }
            }
            if (textPutCode != 0) {
                logger.error("获取转换数据失败");
                //获取转换数据失败
                return;
            }
            //定位到文件起始位置
            raf.seek(0);
            //写入真实头格式
            raf.write(getWavHeader(dataSize, 16000, 32000, 1, 16));
            logger.info("写入文件成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sessionId != null) {
                INSTANCE.QTTSSessionEnd(sessionId, "Normal");
            }
            INSTANCE.MSPLogout();
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * @param totalAudioLen 音频数据总大小
     * @param sampleRate    采样率
     * @param byteRate      位元（组）率(每秒的数据量 单位 字节/秒)   采样率(44100之类的) * 通道数(1,或者2)*每次采样得到的样本位数(16或者8) / 8;
     * @param nChannels     声道数量
     * @param weikuan       位宽
     */
    private static byte[] getWavHeader(int totalAudioLen, int sampleRate, int byteRate, int nChannels, int weikuan) {
        long totalDataLen = totalAudioLen + 36;
        byte[] header = new byte[44];
        header[0] = 'R'; // RIFF/WAVE header
        header[1] = 'I';
        header[2] = 'F';
        header[3] = 'F';
        header[4] = (byte) (totalDataLen & 0xff);
        header[5] = (byte) ((totalDataLen >> 8) & 0xff);
        header[6] = (byte) ((totalDataLen >> 16) & 0xff);
        header[7] = (byte) ((totalDataLen >> 24) & 0xff);
        header[8] = 'W';
        header[9] = 'A';
        header[10] = 'V';
        header[11] = 'E';
        header[12] = 'f'; // 'fmt ' chunk
        header[13] = 'm';
        header[14] = 't';
        header[15] = ' ';
        header[16] = 16; // 4 bytes: size of 'fmt ' chunk
        header[17] = 0;
        header[18] = 0;
        header[19] = 0;
        header[20] = 1; // format = 1
        header[21] = 0;
        header[22] = (byte) (nChannels & 0xff);
        header[23] = (byte) ((nChannels >> 8) & 0xff);

        header[24] = (byte) (sampleRate & 0xff);//采样率
        header[25] = (byte) ((sampleRate >> 8) & 0xff);
        header[26] = (byte) ((sampleRate >> 16) & 0xff);
        header[27] = (byte) ((sampleRate >> 24) & 0xff);

        header[28] = (byte) (byteRate & 0xff);//取八位
        header[29] = (byte) ((byteRate >> 8) & 0xff);
        header[30] = (byte) ((byteRate >> 16) & 0xff);
        header[31] = (byte) ((byteRate >> 24) & 0xff);

        int b = weikuan * nChannels / 8;//每次采样的大小
        header[32] = (byte) (b & 0xff); // block align
        header[33] = (byte) ((b >> 8) & 0xff);

        header[34] = (byte) (weikuan & 0xff);//位宽
        header[35] = (byte) ((weikuan >> 8) & 0xff);

        header[36] = 'd';//data
        header[37] = 'a';
        header[38] = 't';
        header[39] = 'a';
        header[40] = (byte) (totalAudioLen & 0xff);
        header[41] = (byte) ((totalAudioLen >> 8) & 0xff);
        header[42] = (byte) ((totalAudioLen >> 16) & 0xff);
        header[43] = (byte) ((totalAudioLen >> 24) & 0xff);
        return header;
    }
}
